'use strict';
var jwt = require('jsonwebtoken');
const Controller = require('egg').Controller;

class LoginController extends Controller {
  async index() {
    const { name, password, username } = this.ctx.request.body;
    // const user = {
    //   id: '0001',
    //   name: 'admin',
    //   password: '123456'
    // }
    console.log('======', username, password)
    // if (user.name === name && user.password === password) {
    if (username) {
      const user = await this.ctx.model.User.findOne({ username, password })
      if (user) {
        this.ctx.session.userId = user._id;
        this.ctx.session.userName = user.username;
        const token = jwt.sign({ id: user._id, name }, 'aaa', { expiresIn: '1d' });
        this.ctx.cookies.set('token', token, {
          maxAge: 1000 * 3600 * 24,
          httpOnly: false, // 默认就是 true
          encrypt: true, // 加密传输
          signed: false
        });
        this.ctx.body = {
          code: 1,
          msg: '登录成功',
          userId: user.id,
          token: token
        };
      }
      else {
        this.ctx.body = {
          code: -1,
          msg: '用户名或密码错误'
        };
      }
    }
    else if (name && password) {
      const user = await this.ctx.model.User.findOne({ name, password })
      if (user) {
        this.ctx.session.userId = user._id;
        this.ctx.session.userName = user.name;
        const token = jwt.sign({ id: user._id, username }, 'aaa', { expiresIn: '1d' });
        this.ctx.cookies.set('token', token, {
          maxAge: 1000 * 3600 * 24,
          httpOnly: false, // 默认就是 true
          encrypt: true, // 加密传输
        });
        this.ctx.body = {
          code: 1,
          msg: '登录成功',
          userId: user.id
        };
      }
      else {
        this.ctx.body = {
          code: -1,
          msg: '用户名或密码错误'
        };
      }
    }

  }

  async register() {
    const { username, password } = this.ctx.request.body;
    // 检查必填字段是否都存在
    if (!username || !password) {
      this.ctx.body = {
        code: -90002,
        msg: '注册失败，缺少必要参数'
      };
      return;
    }
    try {
      // 检查用户是否已存在
      const existingUser = await this.ctx.model.User.findOne({ username });
      if (existingUser) {
        this.ctx.body = {
          code: -90002,
          msg: '注册失败，用户已存在'
        };
        return;
      }
      // 创建新用户
      const newUser = await this.ctx.model.User.create({
        username,
        password
      });
      this.ctx.body = {
        code: 1,
        msg: '注册成功',
        userId: newUser._id
      };
    } catch (err) {
      this.ctx.body = {
        code: -1,
        msg: `注册失败，错误信息: ${err.message}`
      };
    }
  }

  async appRegister() {
    const { name, password } = this.ctx.request.body;
    const user = await this.ctx.model.User.findOne({ name })
    if (user) {
      this.ctx.body = {
        code: -90002,
        msg: "用户已存在"
      };
    } else {
      try {
        const res = await this.ctx.model.User.create({
          name,
          password
        });
        this.ctx.body = {
          code: 1,
          msg: "注册成功"
        };
      } catch (err) {
        this.ctx.body = {
          code: -1,
          msg: err
        };
      }
    }
  }

  async getUser() {
    const token = this.ctx.cookies.get("token", {
      signed: false,
      encrypt: true
    });
    const decoded = jwt.verify(token, "aaa");
    const res = await this.ctx.model.User.findOne({ _id: decoded.id });
    this.ctx.body = {
      code: 1,
      msg: 'ok',
      data: {
        id: res._id,
        username: res.username
      }
    };
  }

  async appGetUser() {
    const token = this.ctx.cookies.get("token", {
      signed: false,
      encrypt: true
    });
    const decoded = jwt.verify(token, "aaa");
    const res = await this.ctx.model.User.findOne({ _id: decoded.id });
    console.log('=======', res.name)
    this.ctx.body = {
      code: 1,
      msg: 'ok',
      data: {
        userId: res._id,
        name: res.name
      }
    };
  }

  async logout() {
    this.ctx.session = null;
    this.ctx.cookies.set('token', '');
    this.ctx.body = {
      code: 1,
      msg: '登出成功'
    };
  }

  async redirect() {
    this.ctx.body = {
      code: -90001,
      msg: '未登录'
    };
  }

  // 修改用户信息接口
  async updateUser() {
    const { ctx } = this;
    const { username, password } = ctx.request.body;
    const token = ctx.cookies.get("token", {
      signed: false,
      encrypt: true
    });

    // 检查 token 是否存在
    if (!token) {
      ctx.body = {
        code: -90007,
        msg: '缺少 token，无法修改信息'
      };
      return;
    }

    try {
      const decoded = jwt.verify(token, "aaa");
      const id = decoded.id;

      const updateFields = {};

      // 检查是否有需要修改的用户名
      if (username) {
        // 检查新用户名是否已存在
        const existingUser = await ctx.model.User.findOne({ username });
        if (existingUser && existingUser._id.toString() !== id) {
          ctx.body = {
            code: -90003,
            msg: '修改失败，用户名已存在'
          };
          return;
        }
        updateFields.username = username;
      }

      // 检查是否有需要修改的密码
      if (password) {
        updateFields.password = password;
      }

      // 如果没有可更新的字段，返回提示
      if (Object.keys(updateFields).length === 0) {
        ctx.body = {
          code: -90004,
          msg: '没有需要修改的信息'
        };
        return;
      }

      // 更新用户信息
      const updatedUser = await ctx.model.User.findByIdAndUpdate(
        id,
        updateFields,
        { new: true }
      );

      if (updatedUser) {
        ctx.body = {
          code: 1,
          msg: '用户信息修改成功'
        };
      } else {
        ctx.body = {
          code: -90005,
          msg: '用户不存在，修改失败'
        };
      }
    } catch (err) {
      if (err.name === 'JsonWebTokenError') {
        ctx.body = {
          code: -90008,
          msg: '无效的 token，无法修改信息'
        };
      } else {
        ctx.body = {
          code: -1,
          msg: `修改失败，错误信息: ${err.message}`
        };
      }
    }
  }
}

module.exports = LoginController;
